package io.aicn.lowcode.controller.dbmanager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.aicn.lowcode.entity.dbmanager.DataSource;
import io.aicn.lowcode.service.dbmanager.IDataSourceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据源配置Controller
 * 
 * @author lowcode-generator
 * @since 2025-01-25
 */
@Slf4j
@RestController
@RequestMapping("/api/dbmanager/datasource")
@Tag(name = "数据源管理", description = "数据源配置的增删改查和连接测试")
public class DataSourceController {

    @Autowired
    private IDataSourceService dataSourceService;

    @Operation(summary = "分页查询数据源列表")
    @GetMapping("/page")
    public ResponseEntity<Map<String, Object>> page(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "数据源名称") @RequestParam(required = false) String name,
            @Parameter(description = "数据库类型") @RequestParam(required = false) String type,
            @Parameter(description = "连接状态") @RequestParam(required = false) String status) {
        
        Page<DataSource> page = new Page<>(current, size);
        QueryWrapper<DataSource> queryWrapper = new QueryWrapper<>();
        
        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("name", name.trim());
        }
        if (type != null && !type.trim().isEmpty()) {
            queryWrapper.eq("type", type.trim());
        }
        if (status != null && !status.trim().isEmpty()) {
            queryWrapper.eq("status", status.trim());
        }
        
        queryWrapper.orderByDesc("create_time");
        
        Page<DataSource> result = dataSourceService.page(page, queryWrapper);
        
        Map<String, Object> response = new HashMap<>();
        response.put("records", result.getRecords());
        response.put("total", result.getTotal());
        response.put("current", result.getCurrent());
        response.put("size", result.getSize());
        response.put("pages", result.getPages());
        
        return ResponseEntity.ok(response);
    }

    @Operation(summary = "查询所有数据源列表")
    @GetMapping("/list")
    public ResponseEntity<List<DataSource>> list(
            @Parameter(description = "数据库类型") @RequestParam(required = false) String type,
            @Parameter(description = "连接状态") @RequestParam(required = false) String status) {
        
        // 使用原生SQL查询，避免config字段问题
        List<DataSource> allList = dataSourceService.listWithoutConfig();
        
        // 手动过滤
        List<DataSource> list = allList.stream()
                .filter(ds -> type == null || type.trim().isEmpty() || type.trim().equals(ds.getType()))
                .filter(ds -> status == null || status.trim().isEmpty() || status.trim().equals(ds.getStatus()))
                .collect(java.util.stream.Collectors.toList());
        return ResponseEntity.ok(list);
    }

    @Operation(summary = "测试数据源查询（简化版）")
    @GetMapping("/debug/test")
    public ResponseEntity<Map<String, Object>> testSimple() {
        try {
            // 使用原生SQL查询，排除config字段
            QueryWrapper<DataSource> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id", "name", "type", "host", "port", "database_name", "username", "status", "create_time", "update_time");
            queryWrapper.orderByDesc("create_time");
            
            List<DataSource> list = dataSourceService.list(queryWrapper);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("count", list.size());
            result.put("data", list);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("测试查询失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    @Operation(summary = "根据ID查询数据源详情")
    @GetMapping("/{id}")
    public ResponseEntity<DataSource> getById(@Parameter(description = "数据源ID") @PathVariable Long id) {
        DataSource dataSource = dataSourceService.getById(id);
        if (dataSource == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(dataSource);
    }

    @Operation(summary = "创建数据源")
    @PostMapping
    public ResponseEntity<Map<String, Object>> create(@RequestBody DataSource dataSource) {
        try {
            // 检查名称是否重复
            if (dataSourceService.existsByName(dataSource.getName(), null)) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "数据源名称已存在: " + dataSource.getName());
                return ResponseEntity.badRequest().body(response);
            }

            DataSource result = dataSourceService.createWithTest(dataSource);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "数据源创建成功");
            response.put("data", result);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("创建数据源失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "创建失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @Operation(summary = "更新数据源")
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> update(
            @Parameter(description = "数据源ID") @PathVariable Long id,
            @RequestBody DataSource dataSource) {
        try {
            DataSource existing = dataSourceService.getById(id);
            if (existing == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "数据源不存在");
                return ResponseEntity.notFound().build();
            }

            // 检查名称是否重复
            if (dataSourceService.existsByName(dataSource.getName(), id)) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "数据源名称已存在: " + dataSource.getName());
                return ResponseEntity.badRequest().body(response);
            }

            dataSource.setId(id);
            
            // 测试连接并更新状态
            boolean connected = dataSourceService.testConnection(dataSource);
            dataSource.setStatus(connected ? DataSource.Status.CONNECTED.getCode() : DataSource.Status.DISCONNECTED.getCode());
            
            boolean success = dataSourceService.updateById(dataSource);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "更新成功" : "更新失败");
            response.put("data", dataSource);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("更新数据源失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @Operation(summary = "删除数据源")
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> delete(@Parameter(description = "数据源ID") @PathVariable Long id) {
        try {
            boolean success = dataSourceService.removeById(id);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "删除成功" : "删除失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除数据源失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @Operation(summary = "测试数据源连接")
    @PostMapping("/test")
    public ResponseEntity<Map<String, Object>> testConnection(@RequestBody DataSource dataSource) {
        try {
            boolean connected = dataSourceService.testConnection(dataSource);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("connected", connected);
            response.put("message", connected ? "连接成功" : "连接失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("测试连接失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("connected", false);
            response.put("message", "测试失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @Operation(summary = "刷新所有数据源连接状态")
    @PostMapping("/refresh-all")
    public ResponseEntity<Map<String, Object>> refreshAllStatus() {
        try {
            String result = dataSourceService.refreshAllStatus();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", result);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("刷新连接状态失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "刷新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}